package com.ytxg.health_management.service.impl;

import com.ytxg.health_management.mapper.UserMapper;
import com.ytxg.health_management.pojo.dto.UserDto;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.pojo.entity.User;
import com.ytxg.health_management.pojo.vo.UserRegister;
import com.ytxg.health_management.service.UserService;
import com.ytxg.health_management.util.*;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${images.replace}")
    private String baseUrl;
    /**
     * 注册
     *
     */
    @Override
    public int register(UserRegister user) {
        User user1 = new User();
        if (user.getNickName() == null|| user.getNickName().isEmpty()) {
            user1.setNickName(RandomUsernameGenerator.generateRandomUsername());
        } else {
            user1.setNickName(user.getNickName());
        }
        user1.setUserName(user.getUserName())
                .setPassword(user.getPassword())
                .setLevel(0)
                .setSex(3)
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                .setStatus(1)
                .setImg("/img/system/download?fileName=a8c24f2e-1165-410e-8fe6-caee1783f6a2.jpg");
        return userMapper.register(user1);
    }

    /**
     * 查找用户名存不存在
     *
     */
    @Override
    public String getUserName(String userName) {
        return userMapper.getUserName(userName);
    }


    /**
     * 登录
     */
    @Override
    public Result<Map<String,Object>> login(UserRegister userRegister) {

        User userInfo = userMapper.getUserInfo(userRegister.getUserName());
        if(userInfo==null){
            throw new MyException(ResultCode.USER_NOT_FIND, Const.USER_NOT_FOUND);
        }

        if(userInfo.getStatus()==2){
            throw new MyException("该用户已被封禁");
        }

        if (userRegister.getPassword().equals(userInfo.getPassword())) {
            Map<String, String> map = new HashMap<>();
            map.put("username", userRegister.getUserName());
            map.put("password", userInfo.getPassword());
            String token = JWTUtils.getToken(map);
            HashMap<String, Object> res = new HashMap<>();
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(userInfo, userDto);
            res.put("token", token);
            res.put("user", userDto);
            return Result.success("登录成功", res);
        }
        throw new MyException("账号或密码错误");
    }


    /**
     * 获取用户信息
     */
    @Override
    public UserDto  getUserInfo(String userName) {
        UserDto userDto = new UserDto();
        User userInfo = userMapper.getUserInfo(userName);
        userDto.setUserName(userInfo.getUserName())
                .setNickName(userInfo.getNickName())
                .setId(userInfo.getId())
                .setStatus(userInfo.getStatus())
                .setSex(userInfo.getSex())
                .setBirthday(userInfo.getBirthday())
                .setImg(userInfo.getImg())
                .setLevel(userInfo.getLevel());
        return userDto;
    }

    /**
     * 修改密码
     */
    @Override
    public Result<String> updatePsw(String userName,User user) {
        try {
            userMapper.updatePsw(userName,user.getPassword());
            return Result.success("修改成功",null);
        }catch (Exception e){
            return Result.fail("修改失败");
        }
    }

    /**
     * 获取所有用户
     */
    @Override
    public Result<Map<String,Object>> getAll(User user) {
        if(user.getCurrentPage()!=null && user.getPageSize()!=null) {
            user.setCurrentPage((user.getCurrentPage()-1)*user.getPageSize());
        }
        List<UserDto> all = userMapper.getAll(user);
        int total = userMapper.getCountAll(user);
        HashMap<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("userList", all);
        return Result.success(res);
    }

    /**
     * 修改头像
     */
    @Override
    public Result<String> updateImg(String img, int id) {

        try {
            String replace = img.replace(baseUrl, "");
            userMapper.updateImg(replace,id);
            return Result.success("头像更新成功",replace);
        } catch (Exception e) {
            throw new MyException("头像更新失败"+e);
        }

    }

    @Override
    public Result<String> updateUser(User user) {
        int i = userMapper.updateUser(user);
        return Result.success("成功");
    }

    @Override
    public Result<String> deleteUser(User user) {
        userMapper.deleteUser(user);
        return Result.success("成功");
    }


}
